function getUrlParam(name,defaultValue) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return defaultValue; //返回参数值
}
function getNav(type){
    var obj = [];
    if(type.indexOf(0)!=-1) {
        obj.push({
            "name": "",
            "scheme": "http://"+window.location.host+"/show/shoppingCart",
            "icon": "http://irun.hupu.com/static/images/icon/ic_navbar_gwc_nor.png",
            "position": 0
        });
    }
    if(type.indexOf(2)!=-1) {
        obj.push({
            "name": "",
            "scheme": "http://"+window.location.host+"/show/shoppingCart",
            "icon": "http://irun.hupu.com/static/images/icon/ic_navbar_gwc2_nor.png",
            "position": 0
        });
    }
    if(type.indexOf(1)!=-1) {
        obj.push({
            "name": "返回首页",
            "scheme": "joggers://wv_gear_home",
            "icon": "http://irun.hupu.com/static/images/icon/ic_more_hdsy.png",
            "position": 1
        });
    }
    obj.push({
        "name": "刷新",
        "scheme": "joggers://wv_refresh",
        "icon": "http://irun.hupu.com/static/images/icon/ic_more_shuaxin.png",
        "position": 1
    });
    obj.push({
        "name": "复制链接",
        "scheme": "joggers://wv_copy_url",
        "icon": "http://irun.hupu.com/static/images/icon/ic_more_lianjie.png",
        "position": 1
    });
    obj.push({
        "name": "分享",
        "scheme": "joggers://wv_share",
        "icon": "http://irun.hupu.com/static/images/icon/ic_more_share.png",
        "position": 1
    });
    obj.push({
        "name": "测一测",
        "scheme": "joggers://gearAdvisor",
        "icon": "http://irun.hupu.com/static/images/icon/ic_more_sousuo.png",
        "position": 1
    });
    obj.push({
        "name": "我的装备库",
        "scheme": "joggers://gearStore",
        "icon": "http://irun.hupu.com/static/images/icon/ic_more_wdzbk.png",
        "position": 1
    });

    return obj;
}
function jump(url,isNewVersion){
    if(typeof jw === "object" && isNewVersion) {
        jw.api('wv_refresh', JSON.stringify({
            "url": url,
        }), '')
    }else{
        location.href = url;
    }
}

var isIwant = false;//装备，想要
function iwant() {
    $('#iwant').on('click', function () {
        if (isIwant) {
            return;
        }
        isIwant = true;
        var _this = $(this);
        var gid = $(this).attr('data-id');
        var action = $(this).attr('data-action');
        $.ajax({
            data: {gid: gid, action: action},
            url: '/show/likes',
            type: 'post',
            success: function (res) {
                isIwant = false;
                if (action == 'query') {
                    $(_this).attr('data-action', (res == 1 ? 'del' : ''));
                    if (res == 1) {
                        $(_this).addClass('on');
                    }
                    return;
                }
                if (res >= 0) {
                    if (action == 'del') {
                        $(_this).attr('data-action', '');
                        $(_this).removeClass('on');
                        toast('已取消收藏');
                        $('.wantbox em').html(res);
                    } else {
                        $(_this).attr('data-action', 'del');
                        $(_this).addClass('on');
                        toast('已收藏');
                        $('.wantbox em').html(res);
                    }
                } else if (res == -1) {
                    location.href = "joggers://login/";
                }
            }
        })
    });
    $('#iwant').click();
}

var timer = null;
function toast(msg,isNewVersion){
    if(isNewVersion && typeof jw === "object"){
        jw.api('alert', JSON.stringify({
            "title": msg
        }), '')
    }else {
        clearTimeout(timer);
        $(document.body).append('<div id="tips" style="top:70%">' + msg + '</div>');
        $('#tips').fadeIn();
        timer = setTimeout(function () {
            $('#tips').fadeOut(function () {
                $(this).remove()
            });
        }, 1500);
    }
}

function starttimer(currentTime){
    var endTime = 0;
    setInterval(function(){
        currentTime++;
        $('.time').each(function(){
            endTime = parseInt($(this).attr('data-endtime'));
            var prefix = $(this).attr('data-prefix');
            $(this).html(showtime(prefix));
        });
        function showtime(prefix){
            tempTime = endTime - currentTime;

            var d=Math.floor(tempTime/60/60/24);
            var h=Math.floor(tempTime/60/60%24);
            var m=Math.floor(tempTime/60%60);
            var s=tempTime-d*24*3600-h*3600-m*60;

            h = d>=1 ?(h+d*24) : h;
            h = h<10 ? ("0"+h) : h;
            m = m<10 ? ("0"+m) : m;
            s = s<10 ? ("0"+s) : s;
            if(tempTime<0){
                return '';
            }
            var leftTime = '<img src="/static/images/icon/colok.png">'+prefix+' <span>'+h+'</span> : <span>'+m+'</span> : <span>'+s+'</span>';
            return leftTime;
        }

    }, 1000);
}

function initskubutton(){
    $('._buybutton').on('click',function(){
        isaddtocart = $(this).attr('data-shopcart');
        if($(this).attr("data-url")){
            location.href = $(this).attr("data-url");
        }
        if($(this).text()=='立即购买'||$(this).text()=='加入购物车'){
            $('.masklayer').fadeIn(300,function(){
                $('.choice-box').slideDown();
            });
        }
    });

    $('.choice-box').on('click',function(){
        return false;
    })

    $('.masklayer').on('click',function(){
        var _this = $(this);
        $('.choice-box').slideUp(function(){
            $(_this).fadeOut(500);
        });
    });

    var data_index = 1;
    $('.choice-box dd').each(function(){
        $(this).find('span').attr('data-index',data_index++);
    });

    //当sku只有一个的情况下 删除库存为0的商品显示
    if($('.choice-box dd').size()==2){
        $.each(goods,function(k,v){
            var stockNum = v['stockNum']-v['saleNum'];
            var source  = v['attrPathId'].split('—');
            if(stockNum<=0){
                var a = v['attr'][0]['id'];
                $('.choice-box ._color[data-id="'+a+'"]').remove();
            }
        });
    }

    $('.choice-box ._color').on('click',function(){
        if($(this).hasClass('gray')){
            return;
        }
        if($(this).hasClass('on')){
            $(this).removeClass('on');
            refreshButton();
            return;
        }

        var pid = $(this).attr('data-pid');
        var id = $(this).attr('data-id');


        $('.choice-box ._color').each(function(){
            if($(this).attr('data-pid')==pid){
                $(this).removeClass('on');
            }
        });
        $(this).addClass('on');
        refreshButton();
    });

    function refreshButton(){
        gid = '';

        var pathName = [];
        var idStr  = [];
        var img = '';
        $('.choice-box ._color').each(function(){
            if($(this).hasClass('on')){

                pathName.push($(this).text());
                idStr.push($(this).attr('data-id'));

                if(img.length==0)
                    img = $(this).attr('data-img');
            }
        });

        //当sdk大于2时 启用禁用状态
        if($('.choice-box dd').size()>2){
            disableButton(idStr);
        }



        $('#choosetext').text(pathName.length==0? defalt_text : ('已选 '+pathName.join(' ')));
        $('#choosenum').text(defalt_num);
        $('#chooseprice').text(defalt_price);
        $('#chooseimg').attr('src',img ? img : default_img);
        $('.num-box input').val("1");

        var attrPathName = pathName.join('—');
        $.each(goods,function(k,v){
             //var expect = v['attrPathId'].split('—').sort();
            //idStr.sort().join('—') == expect.join('—')
            if(v['attrPathName'] == attrPathName){
                var num = v['stockNum']-v['saleNum'];
                $('#choosenum').text(num<=0 ? 0 : num);
                $('#chooseprice').text('￥'+v['saleprice']);
                gid = v['id'];
            }
        });
    }

    function disableButton(idStr){
        if(idStr.length==0){
            $('.choice-box ._color').removeClass('gray');
            return;
        }

        //移除当前active 行的disable
        $('.choice-box dd').each(function(){
            if($(this).find('on')){
                $(this).find('span').removeClass('gray');
            }
        });

        var gray_arr = {};
        var filter_result = [];
        var diff_result = {};
        $.each(goods,function(k,v){
            var stockNum = v['stockNum'];
            var source  = v['attrPathId'].split('—');
            var diff = array_diff(source,idStr);
            if(array_compare(source,idStr)){
                filter_result.push(v);
                for(var i=0;i<diff.length;i++){
                    diff_result[diff[i]] = 1;
                }
                //console.log(v['attrPathName']+" "+diff);
            }
        });

        console.log(filter_result);
        console.log(diff_result);
        for(var a in diff_result){
            var status = check_isdisable(a);
            if(status){
                $('.choice-box ._color[data-id="'+a+'"]').addClass('gray');
            }else{
                $('.choice-box ._color[data-id="'+a+'"]').removeClass('gray');
            }
        }


        function check_isdisable(id){
            var count1 = 0, count2 = 0;
            var arr = idStr.slice();
            arr.push(id);

            //重新排列顺序
            var obj = {};
            for(var i=0;i<arr.length;i++){
                var index =  $('.choice-box ._color[data-id="'+arr[i]+'"]').attr('data-index');
                obj[index] = arr[i];
            }
            arr = [];
            for(var a in obj){
                arr.push(obj[a]);
            }


            console.log('debug'+arr+"|");
            $.each(filter_result,function(k,v){
                var stockNum = v['stockNum'];
                var source  = v['attrPathId'].split('—');
                console.log("compare "+source+" "+arr +" "+array_compare2(source,arr))
                if(array_compare2(source,arr)){
                    if(idStr.join('—')!=v['attrPathId'])
                        count2++;
                    if(stockNum==0){
                        count1++;
                    }
                }
            });
            console.log("compare result "+count1+" "+count2);
            return count2!=0&&count1 == count2;
        }

        function array_compare2(source,dest){
            var newArr = [];
            for(var i=0;i<source.length;i++){
                var isEqual = false;
                for(var j=0;j<dest.length;j++){
                    if(dest[j]==source[i]){
                        newArr.push(source[i]);
                        break;
                    }
                }
            }
            return newArr.length==dest.length||newArr.length==source.length;
        }

        function array_compare(source,dest){
            var newArr = [];
            for(var i=0;i<source.length;i++){
                var isEqual = false;
                for(var j=0;j<dest.length;j++){
                    if(dest[j]==source[i]){
                        newArr.push(source[i]);
                        break;
                    }
                }
            }
            return newArr.length>0;
            //return newArr.length==dest.length;
        }

        function array_diff(source,dest){
            var newArr = [];
            for(var i=0;i<source.length;i++){
                var isEqual = false;
                for(var j=0;j<dest.length;j++){
                    if(dest[j]==source[i]){
                        isEqual=true;
                        break;
                    }
                }
                if(!isEqual){
                    newArr.push(source[i]);
                }
            }
            return newArr;
        }
    }





    $('.num-box span').on('click',function(){
        var option = $(this).text();
        var val = parseInt($('.num-box input').val());
        if(option=='-'){
            if(val>1){
                $('.num-box input').val(val-1);
            }
        }else if(option=="+"){
            var num = parseInt($('#choosenum').text());
            if(val<num){
                $('.num-box input').val(val+1);
            }
        }
    });

}
function IdentityCodeValid(code) {
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;

    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
        tip = "身份证号格式错误";
        pass = false;
    }

    else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = false;
    }
    else{
        //18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    return pass;
}